package com.hwxm.ltim.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hwxm.ltim.constant.MessageType;
import com.hwxm.ltim.entity.ChatMessage;
import com.hwxm.ltim.entity.GroupMember;
import com.hwxm.ltim.entity.message.MessageRequest;
import com.hwxm.ltim.entity.message.MessageResponse;
import com.hwxm.ltim.mapper.ChatMessageMapper;
import com.hwxm.ltim.mapper.GroupMemberMapper;
import com.hwxm.ltim.util.ChannelManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 聊天消息服务
 */
@Slf4j
@Service
public class ChatMessageService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private GroupMemberMapper groupMemberMapper;

    /**
     * 保存单聊消息
     */
    public void savePrivateMessage(MessageRequest request) {
        ChatMessage message = new ChatMessage();
        BeanUtils.copyProperties(request, message);
        message.setType(MessageType.PRIVATE_CHAT);
        message.setStatus(0); // 未读
        message.setDeleted(0);
        message.setSendTime(LocalDateTime.now());
        message.setCreateTime(LocalDateTime.now());

        chatMessageMapper.insert(message);
    }

    /**
     * 保存群聊消息
     */
    public void saveGroupMessage(MessageRequest request) {
        ChatMessage message = new ChatMessage();
        BeanUtils.copyProperties(request, message);
        message.setType(MessageType.GROUP_CHAT);
        message.setStatus(0); // 未读
        message.setDeleted(0);
        message.setSendTime(LocalDateTime.now());
        message.setCreateTime(LocalDateTime.now());

        chatMessageMapper.insert(message);
    }

    /**
     * 推送离线消息
     */
    public void pushOfflineMessages(Long userId) {
        // 查询用户的离线消息
        LambdaQueryWrapper<ChatMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatMessage::getReceiverId, userId)
                .eq(ChatMessage::getStatus, 0)
                .eq(ChatMessage::getDeleted, 0)
                .orderByAsc(ChatMessage::getSendTime);

        List<ChatMessage> messages = chatMessageMapper.selectList(wrapper);

        if (messages != null && !messages.isEmpty()) {
            log.info("推送离线消息，用户：{}，数量：{}", userId, messages.size());

            for (ChatMessage message : messages) {
                MessageResponse response = MessageResponse.success(
                        message.getType(),
                        "离线消息",
                        message
                );
                String jsonMessage = JSON.toJSONString(response);
                ChannelManager.sendToUser(userId, jsonMessage);
            }
        }
    }

    /**
     * 推送群消息
     */
    public void pushGroupMessage(Long groupId, MessageRequest request) {
        // 查询群成员
        LambdaQueryWrapper<GroupMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GroupMember::getGroupId, groupId);
        List<GroupMember> members = groupMemberMapper.selectList(wrapper);

        if (members != null && !members.isEmpty()) {
            MessageResponse response = MessageResponse.success(MessageType.GROUP_CHAT, "群消息", request);
            String message = JSON.toJSONString(response);

            for (GroupMember member : members) {
                // 不推送给发送者自己
                if (!member.getUserId().equals(request.getSenderId())) {
                    if (ChannelManager.isOnline(member.getUserId())) {
                        ChannelManager.sendToUser(member.getUserId(), message);
                    }
                }
            }
        }
    }

    /**
     * 标记消息为已读
     */
    public void markMessageAsRead(String msgId, Long userId) {
        LambdaQueryWrapper<ChatMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatMessage::getMsgId, msgId)
                .eq(ChatMessage::getReceiverId, userId);

        ChatMessage message = new ChatMessage();
        message.setStatus(1); // 已读

        chatMessageMapper.update(message, wrapper);
    }

    /**
     * 获取聊天历史记录
     */
    public List<ChatMessage> getChatHistory(Long userId1, Long userId2, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<ChatMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w -> w
                .and(w1 -> w1.eq(ChatMessage::getSenderId, userId1).eq(ChatMessage::getReceiverId, userId2))
                .or(w2 -> w2.eq(ChatMessage::getSenderId, userId2).eq(ChatMessage::getReceiverId, userId1))
        );
        wrapper.eq(ChatMessage::getDeleted, 0)
                .orderByDesc(ChatMessage::getSendTime)
                .last("limit " + (pageNum - 1) * pageSize + ", " + pageSize);

        return chatMessageMapper.selectList(wrapper);
    }
}

